<?php

namespace api\ygzc\model;

use think\Model;
use think\facade\Db;
use Qiniu\Auth;
use Qiniu\Storage\UploadManager;

class UploadQiniuModel extends Model
{
	private $config;
	public function __construct()
    {
        $pluginClass = cmf_get_plugin_class('Qiniu');
        $this->plugin  = new $pluginClass();
        $this->config  = $this->plugin->getConfig();
    }

	public function get_content_img_url($post_content=''){
		$imgs = cmf_get_content_images($post_content);  //获取html文本里的img
		$str = '';
		if($imgs){
			foreach($imgs as $key=>$val){
				if($key < 3){
					$img_url = $this->upload_cg_img($val['src']);
					if($img_url){
						$str .= '<img src="'.cmf_get_image_url($img_url).'"/>';
					}else{
						$str .= '<img src="'.$val['src'].'"/>';
					}
				}
			}
		}else{
			$str = $post_content;
		}
		return $str;
	}
	
	/*
     * @ 上传远端图片
     * */
    public function upload_cg_img($imgUrl) 
    {
		//$imageData = $this->get_img($imgUrl); //读取网上图片内容
        $imageData = $this->getImgData($imgUrl); //读取网上图片内容
		if($imageData == false){
			return false;
		}
        $auth  = new Auth($this->config['accessKey'], $this->config['secretKey']); 
        $token = $auth->uploadToken($this->config['bucket']);
        $key   = 'mjyx_cg_image_'.time().rand(1000,9999).'.jpg'; //上传的文件名
        $up    = new UploadManager();
        $mime  = 'image/jpeg';
        list($rest, $err) = $up->put($token, $key, $imageData, null, $mime);
        if ($err) {
			return false;
        } else {
            $domain = $this->config['protocol']."://".$this->config['domain']."/"; //获取上传到七牛云的图片url
            $uploadUrl = $domain.$rest['key'];
			return $uploadUrl;
        }
    }  
	
	
	function getImgData($imgUrl)
    {
		/*$ch = curl_init($imgUrl);
        curl_setopt($ch, CURLOPT_HEADER, 0);
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
        curl_setopt($ch, CURLOPT_BINARYTRANSFER, 1);
        curl_setopt($ch, CURLOPT_FOLLOWLOCATION, 0);
        $rawData = curl_exec($ch); //读取图片信息
        curl_close($ch); */
		$ch = curl_init();
		curl_setopt($ch, CURLOPT_POST, 0); 
		curl_setopt($ch,CURLOPT_URL,$imgUrl);
		curl_setopt($ch, CURLOPT_TIMEOUT, 5); 
		curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1); 
		$rawData = curl_exec($ch);
		curl_close($ch);
        return $rawData;
    }
	
	

}